// pages/login/index.js
import Toast from '../../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../../utils/storage';
const $api = require('../../../../../request/api').API;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    openId: '',
    loginType: 20, //1账号密码登录，10手机号验证码登录，20根据openId快捷登录
    phone: '',
    code: '',
    // 同意协议
    agreement: false,
    // 倒计时
    second: 0,
    isSwitch: false // true表示是自动登录，false是退到登录页面自动去登录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 这里需要判断是不是从切换用户进来的
    const { isSwitch } = options;
    if (isSwitch) {
      this.setData({
        isSwitch
      });
    }
    !isSwitch && this.login();

    // 确保获取到openId
    // if(!openId){

    //   app.openIdCallback = (openId) => {
    //     if (openId) {
    //       this.setData({
    //         openId,
    //       })
    //       if(!isSwitch){
    //         this.login()
    //       }
    //     }
    //   }
    // }else{
    //   this.setData({
    //     openId,
    //   })
    //   if(!isSwitch){
    //     this.login()
    //   }
    // }
  },
  // 删除输入
  deleteInput() {
    this.setData({
      phone: ''
    });
  },
  //  同意协议
  agreementChange(e) {
    this.setData({
      agreement: !this.data.agreement
    });
  },
  // 去协议查看页面
  clickAgreementText() {
    wx.navigateTo({
      url: '/pages/login/customerAgreement/index'
    });
  },
  // 切换登录类型
  loginChange(e) {
    this.setData({
      loginType: e.currentTarget.dataset.type
    });
  },
  // 获取验证码
  getcode() {
    var _this = this;
    if (_this.data.phone.length != 11) {
      wx.showToast({
        icon: 'none',
        title: '手机号不正确'
      });
      return;
    }
    if (_this.data.second > 0) {
      return;
    }
    let params = {
      mobile: this.data.phone,
      smsType: 101,
      useType: 1
    };
    $api.getPhoneCode(params).then(res => {
      console.log('获取验证码的回调', res);
      if (res.data.status == 0) {
        wx.showToast({
          title: '发送验证码成功',
          status: 'success'
        });

        _this.setData({
          second: 60
        });
        _this.timer = setInterval(function () {
          _this.setData({
            second: _this.data.second - 1
          });
          if (_this.data.second == 0) {
            clearInterval(_this.timer);
          }
        }, 1000);
      }
    });
  },
  // 登录注册验证
  verifyForm() {
    if (!this.data.phone && this.data.loginType == 10) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号'
      });
      return false;
    }
    // 验证码登录
    if (!this.data.code && this.data.loginType == 10) {
      wx.showToast({
        icon: 'none',
        title: '请输入验证码'
      });
      return false;
    }
    if (!this.data.agreement && this.data.isSwitch) {
      wx.showToast({
        icon: 'none',
        title: '请先勾选协议'
      });
      return false;
    }
    return true;
  },
  // 登录
  async login() {
    let openId = wx.getStorageSync(Storage.USER_OPEN_ID);
    if (!openId) {
      // 这里不存在openId,说明断网了，执行这里
      await app.init();
      // openId = wx.getStorageSync(Storage.USER_OPEN_ID)
    }
    if (!this.verifyForm()) return;
    let params = {
      code: this.data.code,
      userName: this.data.phone,
      loginType: this.data.loginType
    };
    app.login(() => {
      Toast.clear();
      Toast.success({
        message: '登录成功',
        forbidClick: true,
        duration: 1000,
        onClose() {
          wx.reLaunch({
            url: '/pages/home/index'
          });
        }
      });

      // 先判断是否有呼叫器Code,有就说明是扫码进小程序的
      // if(app.globalData.share){
      //   //判断是否从分享页跳转来的
      //   setTimeout(() => {
      //     wx.reLaunch({
      //       url: '/pages/index/share/index',
      //     })
      //   }, 1000);
      // }else if(app.globalData.qrcode){
      //   wx.reLaunch({
      //     url: '/subcontract/order/pages/pay/index',
      //   })
      // }else if(app.globalData.promoterCode){
      //   setTimeout(()=>{
      //     wx.reLaunch({
      //       url: '/pages/person/authPromoter/index',
      //     })
      //   },1000)
      // }else if(app.globalData.applyBeeperCode){
      //   wx.reLaunch({
      //     url: '/subcontract/person/pages/authApply/index',
      //   })
      // }else if(app.globalData.villageId){
      //   wx.reLaunch({
      //     url: '/subcontract/equipment/pages/beeperVillageCode/index',
      //   })
      // }else{
      //   setTimeout(() => {
      //     wx.reLaunch({
      //       url: '/pages/home/index',
      //     })
      //   }, 1000);
      // }
    }, params);
    // const res = await $api.userLogin(params)
    // if (res.data.status == 0) {
    // 写入token
    // const {userCode,userRole,detailRole,imageUrl,nickName,userId,level,phone,casUserId} = res.data.data
    // // 详细角色区分专属商户
    // wx.setStorageSync(Storage.ACCESS_TOKEN, userCode)
    // wx.setStorageSync(Storage.USER_ROLE, userRole)
    // wx.setStorageSync(Storage.USER_ID, userId)
    // wx.setStorageSync(Storage.DETAIL_ROLE, detailRole)
    // wx.setStorageSync(Storage.LEVEL,level)
    // wx.setStorageSync(Storage.PHONE,phone)
    // wx.setStorageSync(Storage.AVATAR_URL,imageUrl)
    // wx.setStorageSync(Storage.NICK_NAME,nickName)
    // wx.setStorageSync(Storage.CAS_USER_ID,casUserId)
    // 执行socket
    // app.initSocket()
    // }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  // 输入框绑定值
  phoneInput(e) {
    let value = e.detail.value;
    this.setData({
      phone: value
    });
  },
  passwordInput(e) {
    let value = e.detail.value;
    this.setData({
      password: value
    });
  },
  codeInput(e) {
    let value = e.detail.value;
    this.setData({
      code: value
    });
  }
});
